package util
{
	import flash.errors.*;
	import flash.events.*;
	import flash.external.*;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	
	import mx.collections.ArrayList;
	import mx.controls.AdvancedDataGrid;
	import mx.controls.Alert;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumnGroup;
	import mx.controls.dataGridClasses.DataGridColumn;
	
	import spark.components.DataGrid;
	import spark.components.gridClasses.GridColumn;

	public class ExportExcel
	{
		public function ExportExcel()
		{
		}
		
		/** 在导出数据的时候有可能出现单元格数据长度过长而导致Excel在显示时   
		 *  出现科学计数法或者#特殊符号，在此设置单元格宽度比例WIDTHSCALE，在   
		 *  代码中每个单元格的宽度扩展适当的比例值WIDTHSCALE。   
		 */   
		private static var WIDTHSCALE:Number=1.0;   
	
		private static var strChild:String="";
		/**   
		 * 将DataGrid转换为htmltable   
		 * @param: dg 需要转换成htmltable的DataGrid   
		 * @return: String   
		 */   
		private static function convertDGToHTMLTable(dg:spark.components.DataGrid):String {   
			//设置默认的DataGrid样式   
			var font:String = dg.getStyle('fontFamily');   
			var size:String = dg.getStyle('fontSize');   
			var str:String = '';   
			var colors:String = '';   
			var style:String = 'style="font-family:'+font+';font-size:'+size+'pt;"';                   
			var hcolor:Array;   
			
			//检索DataGrid的 headercolor   
			if(dg.getStyle("headerColor") != undefined) {   
				hcolor = [dg.getStyle("headerColor")];   
			} else {   
				hcolor = dg.getStyle("headerColors");   
			}                  
			
			//   Alert.show(hcolor+"");
			var x :String = "" ;
			if(hcolor == null){
				x = "0x323232" ;
			}else{
				x = Number((hcolor[0])).toString(16);
			}
			str+="<style　type='text/css'>.format{mso-number-format:'\@';}</style>";
			//   str+= '<table width="'+dg.width+'" border="1"><thead><tr width="'+dg.width+'" style="background-color:#' +Number((hcolor[0])).toString(16)+'">';   
			str+= '<table align="center" width="'+dg.width+'" border="1"><thead><tr width="'+dg.width+'" style="background-color:#' +x+'">';  
			var sourceList:ArrayList=dg.columns as ArrayList;
			//设置tableheader数据(从datagrid的header检索headerText信息)     //从第2列形如，第一列为操作列             
			for(var i:int = 1;i<sourceList.length;i++) {   
				colors = dg.getStyle("themeColor");   
			
				if(sourceList.source[i].dataField == null || sourceList.source[i].dataField == ""){}else{ //表示不是操作列
					if(sourceList.source[i].visible == true){
						if(sourceList.source[i].headerText != undefined) {   
							str+="<th "+style+">"+sourceList.source[i].headerText+"</th>";   
						} else {   
							str+= "<th "+style+">"+sourceList.source[i].dataField+"</th>";   
						} 
					}
				}
				
			}   
			str += "</tr></thead>";   
			colors = dg.getStyle("alternatingRowColors");   
			
			for(var j:int =0;j<dg.dataProvider.length;j++) {                    
				str+="<tr width=\""+Math.ceil(dg.width)+"\">";   
				
				for(var k:int=1; k < sourceList.length; k++) {   
					
					if(dg.dataProvider.getItemAt(j) != undefined && dg.dataProvider.getItemAt(j) != null) {   
						if((sourceList.source[k] as GridColumn).dataField == null || (sourceList.source[k] as GridColumn).dataField == ""){}else{   //表示的是字段列
							if(sourceList.source[k].visible == true){
								if((sourceList.source[k] as GridColumn).labelFunction != undefined) { 
									var dataGridColumn:GridColumn = sourceList.source[k] as GridColumn ;
									//       str += "<td width=\""+Math.ceil((sourceList[k] as GridColumn).width*WIDTHSCALE)+"\" "+style+">"+(sourceList[k] as GridColumn).labelFunction(dg.dataProvider.getItemAt(j),sourceList[k].dataField)+"</td>"; 
									str += "<td align='center' width=\""+Math.ceil(dataGridColumn.width*WIDTHSCALE)+"\" "+style+ " Class='format'>"+dataGridColumn.labelFunction(dg.dataProvider.getItemAt(j),dataGridColumn)+"</td>";
									//       //"+sourceList[k].labelFunction(dg.dataProvider.getItemAt(j),sourceList[k].dataField)+"
								} else {   
									str += "<td align='center' width=\""+Math.ceil(sourceList.source[k].width*WIDTHSCALE)+"\" "+style+ " Class='format'>"+(dg.dataProvider.getItemAt(j)[(sourceList.source[k] as GridColumn).dataField] == null ?" ":dg.dataProvider.getItemAt(j)[(sourceList.source[k] as GridColumn).dataField])+"</td>";   
								} 
								
							}
						}
					}   
				}   
				str += "</tr>";   
			}   
			str+="</table>";   
			
			return str;   
		}   
		
		
		/**
		 * AdvancedDataGrid没有合并单元格
		 * **/
		private static function getAdvancedDGColMergeCellsNot(dg:AdvancedDataGrid,style:String,str:String):String{
			var colors:String = '';
			for(var i:int = 0;i<dg.columns.length;i++) {
				colors = dg.getStyle("themeColor");
				if(dg.columns[i].visible == true){
					
					if(dg.columns[i].headerText != undefined) {
						str+="<th "+style+">"+dg.columns[i].headerText+"</th>";
					} else {
						str+= "<th "+style+">"+dg.columns[i].dataField==null?"":dg.columns[i].dataField+"</th>";
					}
				}
			}
			return str ;
		}
		private static var colspan:int=0;
		private static function getColspan(adgc:*):int{
			colspan+=adgc.children.length;
			for(var i:int=0;i<adgc.children.length;i++){
				if(adgc.children[i].hasOwnProperty("children")){
					colspan=colspan-1;//还有子，当前列不算在内
					//colspan+=adgc.children[i].children.length;
					getColspan(adgc.children[i]);
				}
			}
			return colspan;
		}
	
		private static var num :int=0;
		private static function getAllChild(adgc:*):String{
			
			var strTitle:String="";
			if(adgc.hasOwnProperty("children"))
			{
	
				getColspan(adgc);
				strTitle+= '<th colspan='+colspan+'>';
				
				strTitle+='<table width="'+adgc.width+'" border="1"><thead>' +
					'	<tr width="'+adgc.width+'">';
				strTitle+='<th  colspan='+colspan+'>'+adgc.headerText+'</th></tr>';
				colspan=0;
				if(adgc.children.length>0){
					strTitle+='<tr>'
					for(var i:int=0;i<adgc.children.length;i++){
						
						if(adgc.children[i].hasOwnProperty("children")){
							num++;
							strChild+=strTitle;
							strTitle="";
							getAllChild(adgc.children[i]);
						}
						else{
							if(num>0){
								
								strTitle+='<th>'+adgc.children[i].headerText+'</th>';
							}
							else{
								strTitle+='<th>'+adgc.children[i].headerText+'</th>';
							}
						}
						
					}
					strTitle+='</tr>'
				}
				strTitle += '</thead></table></th>';
			}
			else{
				strTitle+='<th>'+adgc.headerText+'</th>';
			}
			if(num>0)
			{
				strChild+=strTitle;
				return strChild ;
			}
			else{
				return strTitle;
			}
		}

		
		private static function getAdvancedDGColMergeCellsYes(dg:AdvancedDataGrid,style:String,str:String,hcolor:Array):String{
			var colors:String = '';
			for(var i:int = 0;i<dg.groupedColumns.length;i++) {
				num=0;
				colspan=0;
				strChild="";
			
				str+=getAllChild(dg.groupedColumns[i]);
			}
			return str ;
		}
		
		/**
		 * AdvancedDataGrid导出excel
		 * 1.支持不合并的情况
		 * 1.支持标题合并列的情况
		 * 
		 * **/
		public  static function convertAdvancedDGToHTMLTable(dg:AdvancedDataGrid,hStr:String):String {
			var font:String = dg.getStyle('fontFamily');
			var size:String = dg.getStyle('fontSize');
			var str:String = '';
			var colors:String = '';
			var style:String = 'style="font-family:'+font+';font-size:'+size+'pt;"';               
			var hcolor:Array;
			//Retrieve the headercolor
			if(dg.getStyle("headerColor") != undefined) {
				hcolor = [dg.getStyle("headerColor")];
			} else {
				hcolor = dg.getStyle("headerColors");
			}               
			//style="font-size:18pt;fontWeight=bold"
			//Set the htmltabel based upon knowlegde from the datagrid
			str+= '<table width="'+dg.width+'" border="1"><caption align=center ><span style="font-size:18pt;fontWeight=bold">'+hStr+'</span></caption><thead><tr width="'+dg.width+'" style="background-color:#' +Number((hcolor[0])).toString(16)+'">';
			//Set the tableheader data (retrieves information from the datagrid header        
			
			//获取AdvancedDataGrid的列
			if(dg.groupedColumns.length == dg.columns.length){ //表示没有合并单元格
				str = getAdvancedDGColMergeCellsNot(dg,style,str);
			} else { //表示合并了单元格
				str = getAdvancedDGColMergeCellsYes(dg,style,str,hcolor);
			}
			
			str += "</tr></thead><tbody>";
			colors = dg.getStyle("alternatingRowColors");
			//循环获取记录
			//将行信息插入table
			for(var j:int =0;j<dg.dataProvider.length;j++) {                   
				str+="<tr>";
				for(var k:int=0; k < dg.columns.length; k++) {
					if( dg.columns[k].visible==true){
						                 
						if(dg.dataProvider.getItemAt(j) != undefined && dg.dataProvider.getItemAt(j) != null) {
						
							if(dg.columns[k].labelFunction != undefined) {
								str += "<td text-align='center'  "+style+">"+dg.columns[k].labelFunction(dg.dataProvider.getItemAt(j),dg.columns[k])==null?"":dg.columns[k].labelFunction(dg.dataProvider.getItemAt(j),dg.columns[k])+"</td>";
							} else {
								
								str += "<td text-align='center' width=\""+Math.ceil(dg.columns[k].width)+"\" "+style+">"+(dg.columns[k].dataField == null ? " " : dg.dataProvider.getItemAt(j)[dg.columns[k].dataField.toString()])+"</td>";
							}
						}
					}
				}
				str += "</tr>";
			}
			str+="</tbody></table>";
			
		
			
			return str;
		} 
		
		/**   
		 * 将制定的DataGrid加载到Excel文件，此方法传入一个htmltable字符串参数到后台Script脚本，然后浏览器给用户提供一个Excel下载    
		 * @params dg 需要导入的数据源DataGrid   
		 * @params url excel文件下载路径   
		 */   
		public function loadDGInExcel(dg:*,url:String,title:String=''):void {   //去掉static
			
			//设置URLVariables参数变量，动态增加属性htmltable   
			var variables:URLVariables = new URLVariables();
			if(dg is DataGrid||dg is OperateDataGrid){
				variables.htmltable = convertDGToHTMLTable(dg);   
			}else if (dg is AdvancedDataGrid) {
				variables.htmltable = convertAdvancedDGToHTMLTable(dg,title);  
			}
			if(title!=""){
				variables.title =encodeURIComponent(title);
			}
			
			var u:URLRequest = new URLRequest(url);   
			u.data = variables;   
			u.method = URLRequestMethod.POST;   
			
			navigateToURL(u,"_self");
			//"_self" 指定当前窗口中的当前帧。    
			//"_blank" 指定一个新窗口。    
			//"_parent" 指定当前帧的父级。    
			//"_top" 指定当前窗口中的顶级帧。   
		}
		
		 public function downloadAttach(item:Object,url:String):void{  
			//var str:String=item.FILE_PATH;  
			
			//方法一：弹出新容器用java类返回  
			//var url:String=serverUrl+downloadAction+"?relPath="+str.substr(0,str.indexOf("/"))+"&filename="+item.FILE_NAME;  
			//navigateToURL(new URLRequest(url), "_blank");  
			
			//方法二：用filerefernce  
			var fileRef: FileReference=new FileReference();
			var urlReq:String=url+encodeURIComponent(item.模板名称);;  
			fileRef.download(new URLRequest(urlReq));  
		}  
	
	
		
	}
}


